package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.mine.model.UserInfo;
import com.meitianhui.convenitenbuy.module.order.ui.activity.OrderPayActivity;
import com.meitianhui.convenitenbuy.module.store.contract.CouponPayContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.CouponCardInfo;
import com.meitianhui.convenitenbuy.module.store.presenter.CouponPayPresenter;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.ReceiveSuccessDialog;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/11/29.
 */

public class CouponPayActivity extends BaseToolbarActivity implements CouponPayContract.View {
    private EditText mEtBuyNumber;
    private TextView mTvAllMoney, mTvPayMoney;
    private String mStoreId, mStoreName;
    private CouponCardInfo.Coupon mCoupon;
    private int mType = -1;
    private String mPayMoney;

    @Inject
    CouponPayPresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_coupon_pay;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        mEtBuyNumber = getViewById(R.id.et_buy_number);
        RxUtils.bindEvents(getViewById(R.id.tv_del), this);
        RxUtils.bindEvents(getViewById(R.id.tv_add), this);
        RxUtils.bindEvents(getViewById(R.id.tv_pay), this);
        mTvAllMoney = getViewById(R.id.tv_all_money);
        mTvPayMoney = getViewById(R.id.tv_pay_money);
        pushPayResult();
        initData();
        mEtBuyNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mCoupon.getCategory_id().equals(Constants.CONS_CASH)) {//现金购买
                    if ("".equals(s.toString()) || "0".equals(s.toString())) {
                        mEtBuyNumber.setText("1");
                        String money = StringUtils.moneyMul("1", mCoupon.getMarket_price());
                        mTvAllMoney.setText("¥" + money);
                        mTvPayMoney.setText("¥" + money);
                        mPayMoney = money;
                    } else {
                        String money = StringUtils.moneyMul(s.toString(), mCoupon.getMarket_price());
                        mTvAllMoney.setText("¥" + money);
                        mTvPayMoney.setText("¥" + money);
                        mEtBuyNumber.setSelection(mEtBuyNumber.getText().length());
                        mPayMoney = money;
                    }
                } else if (mCoupon.getCategory_id().equals(Constants.CONS_LIQUAN)) {//礼券兑换
                    if ("".equals(s.toString()) || "0".equals(s.toString())) {
                        mEtBuyNumber.setText("1");
                        Integer num = Integer.parseInt(mCoupon.getMarket_price_voucher());//礼券面值
                        mTvAllMoney.setText(num + "礼券");
                        mTvPayMoney.setText(num + "");
                        mPayMoney = num+"";
                    } else {
                        Integer num = Integer.parseInt(mCoupon.getMarket_price_voucher());//礼券面值
                        mTvAllMoney.setText((Integer.parseInt(s.toString()) * num) + "礼券");
                        mTvPayMoney.setText((Integer.parseInt(s.toString()) * num) + "");
                        mEtBuyNumber.setSelection(mEtBuyNumber.getText().length());
                        mPayMoney = (Integer.parseInt(s.toString()) * num) + "";
                    }
                }
            }
        });
    }


    private void initData() {
        setTbTitle("支付");
        isEnable(false);
        Intent intent = this.getIntent();
        mStoreId = intent.getStringExtra("store_id");
        mStoreName = intent.getStringExtra("store_name");
        mCoupon = (CouponCardInfo.Coupon) intent.getSerializableExtra("coupon");
        UserInfo userInfo = InfoProvider.getUserInfo(App.getInstance());
        if (userInfo != null) {
            RxTextView.text(getViewById(R.id.tv_phone)).call(userInfo.getMobile());
        }
        RxTextView.text(getViewById(R.id.tv_name)).call(mStoreName);
        if (mCoupon.getCategory_id().equals(Constants.CONS_CASH)) {//现金购买
            RxTextView.text(getViewById(R.id.tv_pay)).call("去支付");
            mTvAllMoney.setText("¥" + mCoupon.getMarket_price());
            mTvPayMoney.setText("¥" + mCoupon.getMarket_price());
            RxView.visibility(getViewById(R.id.tv_should_pay)).call(true);
            String limit = mCoupon.getPer_limit();
            if (!TextUtils.isEmpty(limit)) {
                RxTextView.text(getViewById(R.id.tv_number)).call(limit);
            }
            RxView.visibility(getViewById(R.id.tv_tips)).call(false);
            mType = 0;
            mPayMoney = mCoupon.getMarket_price();
        } else if (mCoupon.getCategory_id().equals(Constants.CONS_LIQUAN)) {//礼券兑换
            RxTextView.text(getViewById(R.id.tv_pay)).call("礼券兑换");
            mTvAllMoney.setText(mCoupon.getMarket_price_voucher() + "礼券");
            mTvPayMoney.setText(mCoupon.getMarket_price_voucher());
            RxView.visibility(getViewById(R.id.tv_coupon)).call(true);
            RxView.visibility(getViewById(R.id.tv_should_pay)).call(false);
            //提示
            String voucherPrice = mCoupon.getMarket_price_voucher();
            if (voucherPrice == null || voucherPrice.equals("0") || voucherPrice.equals("")) {
                RxView.visibility(getViewById(R.id.tv_tips)).call(false);
            } else {
                RxView.visibility(getViewById(R.id.tv_tips)).call(true);
                RxTextView.text(getViewById(R.id.tv_tips)).call("到店消费完成即可获赠" + voucherPrice + "礼券");
            }
            mType = 1;
            mPayMoney = mCoupon.getMarket_price_voucher();
        }
        RxTextView.text(getViewById(R.id.tv_title)).call(mCoupon.getTitle());

    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.tv_add:   //添加
                String num3 = mEtBuyNumber.getText().toString();
                int num_usable=0;//可用优惠券
                try {
                    num_usable=Integer.parseInt(mCoupon.getUsable_num());

                }catch (Exception e){
                    e.printStackTrace();
                }
                int num_per_lim=0;//限购
                try {
                    num_per_lim=Integer.parseInt(mCoupon.getPer_limit());

                }catch (Exception e){
                    e.printStackTrace();
                }
                if (num3.equals("")) {
                    num3 = "0";
                }
                int i_num=Integer.parseInt(num3) + 1;
                if(i_num>num_usable){
                    TipUtils.showToast(App.getInstance(),"超过了优惠卷总数量");
                    break;
                }
                if(num_per_lim>0&&i_num>num_per_lim){
                    TipUtils.showToast(App.getInstance(),"超过了限购数量");
                    break;
                }
                mEtBuyNumber.setText(i_num + "");
                break;
            case R.id.tv_del:   //减
                String num2 = mEtBuyNumber.getText().toString();
                if ("".equals(num2) || "0".equals(num2) || "1".equals(num2)) {
                    return;
                }
                mEtBuyNumber.setText((Integer.parseInt(num2) - 1) + "");
                break;
            case R.id.tv_pay:  //支付
                if (!InfoProvider.getLoginStatus(App.getInstance())) {
                    JumpUtil.jumpToLoginActivity(0, CouponPayActivity.this, 0, "");
                    return;
                }
                if (mType == 0) {//去支付
                    String num = mEtBuyNumber.getText().toString().trim();
                    Integer onSell = Integer.parseInt(mCoupon.getUsable_num());//剩余数量
                    if (Integer.parseInt(num) > onSell) {
                        TipUtils.showToast(App.getInstance(), "库存不足，请重新输入商品数量", 2);
                        mEtBuyNumber.setText("1");
                        return;
                    }

                    Intent intent = new Intent(CouponPayActivity.this, OrderPayActivity.class);
                    intent.putExtra("title", mCoupon.getTitle());
                    intent.putExtra("content", "");
                    intent.putExtra("num", num);
                    intent.putExtra("item_id", mCoupon.getItem_id());
                    intent.putExtra("pay_money", mPayMoney);
                    intent.putExtra("from_page", Constants.TYPE_COUPON);
                    startActivity(intent);
                } else if (mType == 1) {//去兑换
                    if (!InfoProvider.getLoginStatus(App.getInstance())) {
                        JumpUtil.jumpToLoginActivity(0, CouponPayActivity.this, 0, "");
                        return;
                    }
                    Integer num = Integer.parseInt(mEtBuyNumber.getText().toString().trim());
                    presenter.couponExchange(num + "", mCoupon);
                }
                break;

        }

    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {

    }

    private void pushPayResult() {
        Disposable disposable =   RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean != null) {
                    if (payResultBean.result == Constants.PAY_RESULT_SUCCESS) {
                        finish();
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void couponExchangeSuccess() {
        ReceiveSuccessDialog dialog = new ReceiveSuccessDialog(CouponPayActivity.this, R.style.dialog_with_alpha, "恭喜你兑换成功");
        dialog.show();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onFail(int code, String msg) {

        TipUtils.showToast(App.getInstance(),msg);
    }
}
